<template>
  <div class="page">
    <div id="filePicker">选择文件</div>
    <div class="file-panel">
      <h2>文件列表</h2>
      <div class="file-list">
        <ul class="file-item" :class="`file-${file.id}`" v-for="file in fileList">
          <li class="file-type" :icon="fileCategory(file.ext)"></li>
          <li class="file-name">{{file.name}}</li>
          <li class="file-size">{{fileSize(file.size)}}</li>
          <li class="file-status">上传中...</li>
          <li class="file-operate">
            <a title="开始" @click="resume(file)"><i class="icon-sync"></i></a>
            <a title="暂停" @click="stop(file)"><i class="icon-authority"></i></a>
            <a title="移除" @click="remove(file)"><i class="icon-delete"></i></a>
          </li>
          <li class="progress"></li>
        </ul>
        <div class="no-file" v-if="!fileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
      </div>
    </div>

    <vue-upload
      :url="url"
      :formData="videoFormData"
      ref="uploader"
      uploadButton="#filePicker"
      :multiple="true"
      @beforeUpload="beforeUpload"
      @fileChange="fileChange"
      @progress="onProgress"
      @success="onSuccess"
    ></vue-upload>
  </div>
</template>

<script>
  import apiConfig from '../../utils/apiconfig'
  import vueUpload from '../../components/upload'
  import api from '../../utils/api'
  import config from '../../utils/config'
  import WebUploader from '../../../static/lib/webuploader/webuploader.min.js'
  import $ from 'jquery'
  import helper from '../../utils/helper'
  export default {
    data () {
      return {
        fileList: [],
        url: '',
        videoFormData: []
      }
    },
    mounted () {

    },
    computed: {
      uploader () {
        return this.$refs.uploader
      }
    },
    created () {
      this.url = config.domain + helper.getManageApiUrl(apiConfig.fileUpload)
      this.videoFormData = {
        key: '',
        md5: ''
      }
    },
    methods: {
      fileChange (file) {
        console.log('正在计算MD5值...')
        if (!file.size) {
          return
        }
        this.fileList.push(file)
      },
      // 开始上传之前的事件，可以用于断点续传
      beforeUpload (block, data) {
      },

      onProgress (file, percent) {
        $(`.file-${file.id} .progress`).css('width', percent * 100 + '%')
        $(`.file-${file.id} .file-status`).html((percent * 100).toFixed(2) + '%')
      },
      onSuccess (file, response) {
        console.log('上传成功', response)
        let $fileStatus = $(`.file-${file.id} .file-status`)
        $fileStatus.html('上传成功，转码中')
        if (response.errcode === 200) {
          let md5 = response.data.md5
          let fileType = response.data.type
          let param = {
            'md5': md5,
            'file_name': file.name,
            'file_type': fileType
          }
          api.GET(helper.getManageApiUrl(apiConfig.fileMerge), param, res => {
            console.log('上传结果', res)
            if (res.status === 200) {
              $fileStatus.html('上传成功，转码中')
            } else if (res.status === 1) {
              $fileStatus.html('上传失败')
            } else if (res.status === 2) {
              $fileStatus.html('上传成功')
            }
          }, res => {
            console.log(res)
          })
        }
      },

      uploadError (file, reason) {
        this.uploader.retry(file)
      },

      resume (file) {
        this.uploader.upload(file)
      },
      stop (file) {
        this.uploader.stop(file)
      },
      remove (file) {
        // 取消并中断文件上传
        this.uploader.cancelFile(file)
        // 在队列中移除文件
        this.uploader.removeFile(file, true)

        // 在ui上移除
        let index = this.fileList.findIndex(ele => ele.id === file.id)
        this.fileList.splice(index, 1)
      },

      fileSize (size) {
        return WebUploader.Base.formatSize(size)
      },
      fileCategory (ext) {
        let type = ''

        const typeMap = {
          image: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'],
          video: ['mp4', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
          text: ['doc', 'txt', 'docx', 'pages', 'epub', 'pdf', 'numbers', 'csv', 'xls', 'xlsx', 'keynote', 'ppt', 'pptx']
        }

        Object.keys(typeMap).forEach((_type) => {
          const extensions = typeMap[_type]
          if (extensions.indexOf(ext) > -1) {
            type = _type
          }
        })
        return type
      }
    },
    watch: {},
    components: {
      vueUpload
    }
  }
</script>

<style>
  .file-panel {
    width: 840px;
    margin-top: 10px;
    box-shadow: 0 2px 12px 1px rgba(0, 0, 0, 0.1);
  }
  .file-panel h2 {
      height: 40px;
      line-height: 40px;
      padding: 0 10px;
      border-radius: 4px 4px 0 0;
      border-bottom: 1px solid #ccc;
      background-color: #fff;
    }

  .file-panel .file-list {
      position: relative;
      height: 360px;
      overflow-y: auto;
      background-color: rgb(250, 250, 250);
    }

  .file-panel  .file-item {
    position: relative;
    height: 50px;
    line-height: 50px;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    background-color: #fff;
    z-index: 1
  }

  .file-panel  .file-item li {
        display: inline-block;
  }
  .file-panel  .file-type {
      width: 24px;
      height: 24px;
      vertical-align: -5px;
    }
  .file-panel  .file-name {
      width: 40%;
      margin-left: 10px;
  }
  .file-panel  .file-size {
      width: 20%;
  }
  .file-panel .file-status {
      width: 20%;
  }
  .file-panel .file-operate {
    width: 10%;
  }
  .file-panel .file-operate a {
    padding: 10px 5px;
    cursor: pointer;
    color: #666;
  }
  .file-panel .file-operate a:hover {
    color: #ff4081;
  }
  .file-panel  .file-type[icon=text] {
      background: url(../../../src/img/icon/icon-text.png);
  }
  .file-panel .file-type[icon=video] {
      background: url(../../../src/img/icon/icon-video.png);
  }
  .file-panel .file-type[icon=image] {
      background: url(../../../src/img/icon/icon-img.png);
  }

  .file-panel .progress {
      position: absolute;
      top: 0;
      left: 0;
      height: 49px;
      width: 0;
      background-color: #E2EDFE;
      z-index: -1;
    }

  .file-panel .no-file {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 16px;
  }
</style>
